package com.jack.helloworld.activity;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.ViewFlipper;

import com.jack.helloworld.R;


public class ViewFlipperActivity extends AppCompatActivity {

    ViewFlipper viewFlipper;
    int[] viewId;
    float startX;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_flipper);

        initView();
        initData();
    }

    private void initView() {
        viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
    }

    private void initData() {
        viewId = new int[]{R.mipmap.img1, R.mipmap.img2, R.mipmap.img3, R.mipmap.img4, R.mipmap.img5};

        for (int i = 0; i < viewId.length; i++) {
            viewFlipper.addView(getImageView(viewId[i]));
        }
        viewFlipper.setFlipInterval(5000);
        viewFlipper.setInAnimation(this, R.anim.push_right_in);
        viewFlipper.setOutAnimation(this, R.anim.push_left_out);
        viewFlipper.startFlipping();

    }

    private ImageView getImageView (int resId) {
        ImageView imageView = new ImageView(this);
        imageView.setBackgroundResource(resId);
        return  imageView;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                if (startX - event.getX() > 100) {
                    Log.d("jack", "向左划");
                    viewFlipper.setInAnimation(this, R.anim.push_right_in);
                    viewFlipper.setOutAnimation(this, R.anim.push_left_out);
                    viewFlipper.showNext();
                } else if (event.getX() - startX > 100) {
                    Log.d("jack", "向右划");
                    viewFlipper.setInAnimation(this, R.anim.push_left_in);
                    viewFlipper.setOutAnimation(this, R.anim.push_right_out);
                    viewFlipper.showPrevious();
                }
                break;
        }

        return super.onTouchEvent(event);
    }
}
